(function () {

    const status = {
        '0': 'UNSENT',
        '1': 'OPENED',
        '2': 'HEADERS_RECEIVED',
        '3': 'LOADING',
        '4': 'DONE'
    }

    const btn = document.querySelector('#xhr');
    const result = document.querySelector('#result');

    console.log( 1 );

    //let listener = function (event){
    //    console.log( event );
    //}

    let listener = {
        handleEvent() {
            console.log( 2 );
            setTimeout( () => {
                // 创建 XMLHttpRequest 实例
                let $http = new XMLHttpRequest();
                console.log($http.readyState, status[$http.readyState]); // 0 , UNSET
                // 监听 $http 实例上 readyState 的变化(change)
                $http.addEventListener('readystatechange', {
                    handleEvent() {
                        console.log(3);
                        Promise.resolve( $http.readyState ).then( value => {
                            console.log( value , status[value]);
                            if( value === $http.DONE ) {
                                result.innerHTML = $http.response ;
                            }
                        });
                        console.log(4);
                    }
                }, false);
                // 打开连接
                $http.open('post', '/hello'); // $http.readyState: 0 => 1
                // 设置请求头
                $http.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
                // 捏造向服务端发送的数据
                let data = 'username=zhangsanfeng&password=hello';
                // 发送请求(POST请求可以在请求体中包含数据)
                $http.send(data); // $http.readyState: 1 => 2
                console.log(5);
            } , 0);
            console.log(6);
        }
    }

    btn.addEventListener('click', listener, false);

    console.log(7);

})();